<template>
  <div class="dashboard">
    <div class="page-title">系统概览</div>

    <!-- 左右两栏布局 -->
    <el-row :gutter="20">
      <!-- 左侧：人员数据统计 -->
      <el-col :xs="24" :lg="12">
        <div class="section-title">
          <el-icon><User /></el-icon>
          <span>人员数据统计</span>
        </div>
        
        <!-- 人员统计卡片 -->
        <el-row :gutter="10" class="stats-row">
          <el-col :span="6">
            <div class="stat-card personnel-card">
              <div class="stat-title">总记录</div>
              <div class="stat-value">{{ overview.personnel?.total || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card warning">
              <div class="stat-title">待审核</div>
              <div class="stat-value">{{ overview.personnel?.pending || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card success">
              <div class="stat-title">已通过</div>
              <div class="stat-value">{{ overview.personnel?.approved || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card info">
              <div class="stat-title">已驳回</div>
              <div class="stat-value">{{ overview.personnel?.rejected || 0 }}</div>
            </div>
          </el-col>
        </el-row>

        <!-- 人员趋势图 -->
        <div class="page-card chart-card">
          <h4>近7天数据趋势</h4>
          <div ref="personnelChartRef" class="chart-container"></div>
        </div>

        <!-- 人员数据加工统计 -->
        <div class="page-card">
          <h4>近7天数据加工</h4>
          <el-table :data="dailyProcess.personnel" size="small" v-loading="loading">
            <el-table-column prop="date" label="日期" width="100" />
            <el-table-column prop="total" label="总数" width="70" align="center" />
            <el-table-column prop="completed" label="已完成" width="80" align="center">
              <template #default="{ row }">
                <el-tag type="success" size="small">{{ row.completed }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="failed" label="失败" width="70" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.failed > 0" type="danger" size="small">{{ row.failed }}</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="完成率" align="center">
              <template #default="{ row }">
                {{ row.total > 0 ? ((row.completed / row.total) * 100).toFixed(1) + '%' : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 人员审核统计 -->
        <div class="page-card">
          <h4>近7天审核情况</h4>
          <el-table :data="dailyAudit.personnel" size="small" v-loading="loading">
            <el-table-column prop="date" label="日期" width="100" />
            <el-table-column prop="total" label="总数" width="70" align="center" />
            <el-table-column prop="approved" label="通过" width="70" align="center">
              <template #default="{ row }">
                <el-tag type="success" size="small">{{ row.approved }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="rejected" label="驳回" width="70" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.rejected > 0" type="danger" size="small">{{ row.rejected }}</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="通过率" align="center">
              <template #default="{ row }">
                {{ row.total > 0 ? ((row.approved / row.total) * 100).toFixed(1) + '%' : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>

      <!-- 右侧：装备数据统计 -->
      <el-col :xs="24" :lg="12">
        <div class="section-title">
          <el-icon><Box /></el-icon>
          <span>装备数据统计</span>
        </div>
        
        <!-- 装备统计卡片 -->
        <el-row :gutter="10" class="stats-row">
          <el-col :span="6">
            <div class="stat-card weapon-card">
              <div class="stat-title">总记录</div>
              <div class="stat-value">{{ overview.weapon?.total || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card warning">
              <div class="stat-title">待审核</div>
              <div class="stat-value">{{ overview.weapon?.pending || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card success">
              <div class="stat-title">已通过</div>
              <div class="stat-value">{{ overview.weapon?.approved || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card info">
              <div class="stat-title">已驳回</div>
              <div class="stat-value">{{ overview.weapon?.rejected || 0 }}</div>
            </div>
          </el-col>
        </el-row>

        <!-- 装备趋势图 -->
        <div class="page-card chart-card">
          <h4>近7天数据趋势</h4>
          <div ref="weaponChartRef" class="chart-container"></div>
        </div>

        <!-- 装备数据加工统计 -->
        <div class="page-card">
          <h4>近7天数据加工</h4>
          <el-table :data="dailyProcess.weapon" size="small" v-loading="loading">
            <el-table-column prop="date" label="日期" width="100" />
            <el-table-column prop="total" label="总数" width="70" align="center" />
            <el-table-column prop="completed" label="已完成" width="80" align="center">
              <template #default="{ row }">
                <el-tag type="success" size="small">{{ row.completed }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="failed" label="失败" width="70" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.failed > 0" type="danger" size="small">{{ row.failed }}</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="完成率" align="center">
              <template #default="{ row }">
                {{ row.total > 0 ? ((row.completed / row.total) * 100).toFixed(1) + '%' : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 装备审核统计 -->
        <div class="page-card">
          <h4>近7天审核情况</h4>
          <el-table :data="dailyAudit.weapon" size="small" v-loading="loading">
            <el-table-column prop="date" label="日期" width="100" />
            <el-table-column prop="total" label="总数" width="70" align="center" />
            <el-table-column prop="approved" label="通过" width="70" align="center">
              <template #default="{ row }">
                <el-tag type="success" size="small">{{ row.approved }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="rejected" label="驳回" width="70" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.rejected > 0" type="danger" size="small">{{ row.rejected }}</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="通过率" align="center">
              <template #default="{ row }">
                {{ row.total > 0 ? ((row.approved / row.total) * 100).toFixed(1) + '%' : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <!-- 系统健康状态 -->
    <div class="page-card">
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h3>系统健康状态</h3>
        <el-button type="primary" @click="handleRefresh" :loading="refreshing">
          刷新数据
        </el-button>
      </div>
      <el-descriptions :column="3" border style="margin-top: 15px" size="small">
        <el-descriptions-item label="系统状态">
          <el-tag :type="systemStore.health.status === 'ok' ? 'success' : 'danger'">
            {{ systemStore.health.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="数据库">
          <el-tag :type="systemStore.health.database === 'connected' ? 'success' : 'danger'">
            {{ systemStore.health.database }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="检查时间">
          {{ systemStore.health.timestamp ? dayjs(systemStore.health.timestamp).format('HH:mm:ss') : '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useSystemStore } from '@/stores/system'
import { statsApi } from '@/api/stats'
import { User, Box } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

const systemStore = useSystemStore()
const refreshing = ref(false)
const loading = ref(false)
const personnelChartRef = ref(null)
const weaponChartRef = ref(null)
let personnelChart = null
let weaponChart = null

// 总体统计数据
const overview = reactive({
  total: { total: 0, pending: 0, approved: 0, rejected: 0 },
  personnel: { total: 0, pending: 0, approved: 0, rejected: 0 },
  weapon: { total: 0, pending: 0, approved: 0, rejected: 0 }
})

// 每日加工统计
const dailyProcess = reactive({
  personnel: [],
  weapon: []
})

// 每日审核统计
const dailyAudit = reactive({
  personnel: [],
  weapon: []
})

// 获取统计数据
const loadStatistics = async () => {
  loading.value = true
  try {
    // 获取总体统计
    const overviewRes = await statsApi.getOverview()
    if (overviewRes.success) {
      Object.assign(overview, overviewRes.data)
    }

    // 获取每日加工统计
    const processRes = await statsApi.getDailyProcess(7)
    if (processRes.success) {
      dailyProcess.personnel = processRes.data.personnel.map(item => ({
        ...item,
        date: dayjs(item.date).format('MM-DD')
      }))
      dailyProcess.weapon = processRes.data.weapon.map(item => ({
        ...item,
        date: dayjs(item.date).format('MM-DD')
      }))
    }

    // 获取每日审核统计
    const auditRes = await statsApi.getDailyAudit(7)
    if (auditRes.success) {
      dailyAudit.personnel = auditRes.data.personnel.map(item => ({
        ...item,
        date: dayjs(item.date).format('MM-DD')
      }))
      dailyAudit.weapon = auditRes.data.weapon.map(item => ({
        ...item,
        date: dayjs(item.date).format('MM-DD')
      }))
    }
    // 获取趋势数据并渲染图表
    const trendsRes = await statsApi.getTrends(7)
    if (trendsRes.success && trendsRes.data && trendsRes.data.length > 0) {
      await nextTick()
      initCharts(trendsRes.data)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = (trendsData) => {
  if (!trendsData || trendsData.length === 0) {
    return
  }

  const dates = trendsData.map(item => dayjs(item.date).format('MM-DD'))
  
  // 人员趋势图
  if (personnelChartRef.value) {
    if (personnelChart) {
      personnelChart.dispose()
    }
    personnelChart = echarts.init(personnelChartRef.value)
    
    const personnelOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['录入', '加工完成', '审核通过'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '录入',
          type: 'bar',
          data: trendsData.map(item => item.personnel.imported),
          itemStyle: { color: '#409eff' }
        },
        {
          name: '加工完成',
          type: 'bar',
          data: trendsData.map(item => item.personnel.processed),
          itemStyle: { color: '#67c23a' }
        },
        {
          name: '审核通过',
          type: 'line',
          data: trendsData.map(item => item.personnel.approved),
          itemStyle: { color: '#e6a23c' }
        }
      ]
    }
    personnelChart.setOption(personnelOption)
  }

  // 装备趋势图
  if (weaponChartRef.value) {
    if (weaponChart) {
      weaponChart.dispose()
    }
    weaponChart = echarts.init(weaponChartRef.value)
    
    const weaponOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['录入', '加工完成', '审核通过'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '录入',
          type: 'bar',
          data: trendsData.map(item => item.weapon.imported),
          itemStyle: { color: '#409eff' }
        },
        {
          name: '加工完成',
          type: 'bar',
          data: trendsData.map(item => item.weapon.processed),
          itemStyle: { color: '#67c23a' }
        },
        {
          name: '审核通过',
          type: 'line',
          data: trendsData.map(item => item.weapon.approved),
          itemStyle: { color: '#e6a23c' }
        }
      ]
    }
    weaponChart.setOption(weaponOption)
  }

  // 响应式处理
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  personnelChart?.resize()
  weaponChart?.resize()
}

const handleRefresh = async () => {
  refreshing.value = true
  await Promise.all([
    systemStore.checkHealth(),
    loadStatistics()
  ])
  refreshing.value = false
}

onMounted(() => {
  handleRefresh()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  personnelChart?.dispose()
  weaponChart?.dispose()
})
</script>

<style lang="scss" scoped>
.dashboard {
  .section-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid #f0f0f0;

    .el-icon {
      font-size: 22px;
      color: #409eff;
    }
  }

  .stats-row {
    margin-bottom: 20px;
  }

  .stat-card {
    padding: 12px 10px;
    
    &.personnel-card {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.weapon-card {
      background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    }

    .stat-title {
      font-size: 12px;
      margin-bottom: 5px;
    }

    .stat-value {
      font-size: 22px;
      font-weight: 600;
    }
  }

  .chart-card {
    h4 {
      margin: 0 0 15px 0;
      font-size: 14px;
      color: #606266;
    }
  }

  .chart-container {
    width: 100%;
    height: 280px;
  }

  .page-card {
    h4 {
      margin: 0 0 10px 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
  }

  :deep(.el-table) {
    font-size: 12px;

    .el-table__empty-text {
      color: #909399;
    }

    th {
      background-color: #f5f7fa;
    }
  }

  :deep(.el-descriptions) {
    .el-descriptions__label {
      font-weight: 600;
    }
  }
}
</style>


